package com.heaven1949.tmall.common.web.filter;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域处理
 *
 * @author yuandf
 * @description
 * @date 2019/6/20
 */
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //响应头表明该服务器允许哪些源的访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        //用来表明服务器是否允许credentials标志为true的场景
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //用来限制允许的方法名
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        //用来表明预检请求响应的有效时间
        response.setHeader("Access-Control-Max-Age", "86400");
        //用来限制允许的自定义字段名
        response.setHeader("Access-Control-Allow-Headers", "*");
        // 如果是OPTIONS请求则结束
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        return true;
    }

}